var http = require("http");
var fs = require('fs');
var url = require('url');
var doRequest = require('./node/DoRequest.js')

var doPromise = function (req) {
    return new Promise(function (resolve, reject) {
        var result = {}
        req.on('data', function (chunk) {
            var paramGroups = chunk.toString().split("&");
            // console.log('chunk:' + chunk.toString())
            for (var i = 0; i < paramGroups.length; i++) {
                var param = paramGroups[i].split('=');
                result[param[0]] = param[1];
            }
            resolve(result);
        });
    });
}

http.createServer(function (req, res) {
    var pathname = url.parse(req.url).pathname;
    var ext = pathname.match(/(\.[^.]+|)$/)[0];

    if (pathname !== '/' && ext === '') {
        console.log('pathname:' + pathname);

        doPromise(req).then(function (result) {
            console.log('param:', result)
            res.write(doRequest.doRequest(result));
            res.end();
        });

    } else {
        // console.log('ext:' + ext);
        switch (ext) {
            case ".css":
            case ".js":
                fs.readFile("." + req.url, 'utf-8', function (err, data) {
                    if (err) throw err;
                    res.writeHead(200, {
                        "Content-Type": {
                            ".css": "text/css",
                            ".js": "application/javascript",
                        }[ext]
                    });
                    res.write(data);
                    res.end();
                });
                break;
            default:
                fs.readFile('./index.html', 'utf-8', function (err, data) {
                    if (err) throw err;
                    res.writeHead(200, {
                        "Content-Type": "text/html"
                    });
                    res.write(data);
                    res.end();
                });
        }
    }
}).listen(8080);
console.log("server start...");
